/**
 * Copyright (c) 2024-2025 National Fundamental Software of China Co., Ltd.
 *
 * You should have find a copy of NFSChina License. If not, please contact us
 * by email <os_support@nfschina>
 *
**/

/*
    SPDX-FileCopyrightText: 1998 Luca Montecchiani <m.luca@usa.net>
    SPDX-FileCopyrightText: 2015 David Edmundson <davidedmundson@kde.org>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "main.h"
#include <unistd.h>
#include "dtime.h"
#include <QVBoxLayout>
#include<KLocalizedString>
#include <KAboutData>
#include <KMessageBox>
#include <KPluginFactory>
#include <QDBusConnection>
#include <kauth_version.h>
#if KAUTH_VERSION >= QT_VERSION_CHECK(5, 92, 0)
#include <KAuth/Action>
#include <KAuth/ExecuteJob>
#else
#include <KAuthAction>
#include <KAuthExecuteJob>
#endif
#include <QPushButton>
#include "timezone.h"
#include "helper.h"
#include "timedated_interface.h"
#include <KSharedConfig>
#include <KColorScheme>
#include <KConfigGroup>


#include "naviButton.h"
K_PLUGIN_CLASS_WITH_JSON(KclockModule, "kcm_clock.json")

KclockModule::KclockModule(QWidget *parent, const QVariantList &)
    : KCModule(parent)
    , m_configWatcher(KConfigWatcher::create(KSharedConfig::openConfig(QStringLiteral("ktimezonedrc"), KConfig::NoGlobals)))
{
    auto reply = QDBusConnection::systemBus().call(QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.DBus"),
                                                                                  QStringLiteral("/org/freedesktop/DBus"),
                                                                                  QStringLiteral("org.freedesktop.DBus"),
                                                                                  QStringLiteral("ListActivatableNames")));

    if (!reply.arguments().isEmpty() && reply.arguments().constFirst().value<QStringList>().contains(QLatin1String("org.freedesktop.timedate1"))) {
        m_haveTimedated = true;
    }

    m_hwclock = new com::nfs::HwClock("com.nfs.HwClock", "/com/nfs/HwClock", QDBusConnection::systemBus(), this);

    KAboutData *about = new KAboutData(QStringLiteral("kcmclock"),
                                       i18n("KDE Clock Control Module"),
                                       QStringLiteral("1.0"),
                                       QString(),
                                       KAboutLicense::GPL,
                                       i18n("(c) 1996 - 2001 Luca Montecchiani"));

    about->addAuthor(i18n("Luca Montecchiani"), i18n("Original author"), QStringLiteral("m.luca@usa.net"));
    about->addAuthor(i18n("Paul Campbell"), i18n("Current Maintainer"), QStringLiteral("paul@taniwha.com"));
    about->addAuthor(i18n("Benjamin Meyer"), i18n("Added NTP support"), QStringLiteral("ben+kcmclock@meyerhome.net"));
    setAboutData(about);
    setQuickHelp(
        i18n("<h1>Date & Time</h1> This control module can be used to set the system date and"
             " time. As these settings do not only affect you as a user, but rather the whole system, you"
             " can only change these settings when you start the System Settings as root. If you do not have"
             " the root password, but feel the system time should be corrected, please contact your system"
             " administrator."));

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    setButtons(Apply);

    stack.resize(620, 502);
    QWidget *navipage = new QWidget(this);
    QVBoxLayout *navilayout = new QVBoxLayout(navipage);
    navilayout->setSpacing(2);
    //navipage设置大小
    navipage->resize(606, 100);





    NaviButton *button1 = new  NaviButton(this);
    button1->setFixedSize(558, 48); 

    button1->setIcon(QIcon::fromTheme(QStringLiteral("preferences-system-time")),QIcon::fromTheme(QStringLiteral("go-next")));
    button1->setText(i18n("Date and Time"));
    NaviButton *button2 = new  NaviButton(this);
    button2->setFixedSize(558, 48); 
    button2->setIcon(QIcon::fromTheme(QStringLiteral("preference-timezone")),QIcon::fromTheme(QStringLiteral("go-next")));
    button2->setText(i18n("Time Zone"));
    // button1->setIcon(QIcon::fromTheme(QStringLiteral("preferences-system-time")));
    // button2->setIcon(QIcon::fromTheme(QStringLiteral("preferences-system-time")));
    auto config = KSharedConfig::openConfig();
    auto highlitgtscheme = KColorScheme(QPalette::Active, KColorScheme::Selection, config);
    auto active = KColorScheme(QPalette::Active, KColorScheme::View, config);
    QColor thisbackground = active.background().color();
    QColor highlightcolor = highlitgtscheme.background(KColorScheme::NormalBackground).color();
    QColor textcolor = active.foreground(KColorScheme::NormalText).color();
    QString highlightcolorstr = QString("rgb(%1, %2, %3)").arg(highlightcolor.red()).arg(highlightcolor.green()).arg(highlightcolor.blue());
    QString themebackground = QString("rgb(%1, %2, %3)").arg(thisbackground.red()).arg(thisbackground.green()).arg(thisbackground.blue());
    QString themetext = QString("rgb(%1, %2, %3)").arg(textcolor.red()).arg(textcolor.green()).arg(textcolor.blue());
    QString themeborder=themebackground=="rgb(255, 255, 255)"?"rgb(204, 204, 204)":"rgb(45, 45, 45)";
    // QString themeborder="rgb(204, 204, 204)";
    qDebug()<<themebackground;
                                         
    button1->setStyleSheet(QString("QPushButton:hover{ \
                                                background-color:%4;\
                                            }\
                                           QPushButton{ \
                                                background-color:%1;\
                                                font-family: SourceHanSansSC-Regular;\
                                                font-size: 14px;\
                                                padding-left: 54px;\
                                                text-align: left;\
                                                color: %2;\
                                                border-radius : 10px;\
                                                border : 1px solid %3;\
                                            }\
                                            ").arg(themebackground).arg(themetext).arg(themeborder).arg(highlightcolorstr));
    button2->setStyleSheet(QString("QPushButton:hover{ \
                                               background-color:%4;\
                                           }\
                                          QPushButton{ \
                                               background-color: %1;\
                                               font-family: SourceHanSansSC-Regular;\
                                               font-size: 14px;\
                                               padding-left: 54px;\
                                               text-align: left;\
                                               color: %2;\
                                               border-radius : 10px;\
                                               border : 1px solid %3;\
                                           }\
                                           ").arg(themebackground).arg(themetext).arg(themeborder).arg(highlightcolorstr));
    navilayout->addWidget(button1, 0, Qt::AlignHCenter);
    navilayout->addWidget(button2, 0, Qt::AlignHCenter);
    navilayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));

    // 设置布局
    navipage->setLayout(navilayout);
    // 设置 navipage 为可见
    navipage->setVisible(true);
    stack.addWidget(navipage);
    dtime = new Dtime(this, m_haveTimedated);

    dtime->frame->setStyleSheet(QString("QFrame#frame{\
    background-color:%1;\
    border-radius:10px;\
    border: 1px  solid %2;\
    }").arg(themebackground).arg(themeborder));
    dtime->frame_2->setStyleSheet(QString("QFrame#frame_2{\
    background-color:%1;\
    border-radius:10px;\
    border: 1px  solid %2;\
    }").arg(themebackground).arg(themeborder));
    dtime->label->setStyleSheet(QString("border:0px;\
    font-size:14px;\
    font-family: SourceHanSansSC-Regular;\
    color: %1;\
    }").arg(themetext));
    dtime->label_2->setStyleSheet(QString("border:0px;\
    font-size:14px;\
    font-family: SourceHanSansSC-Regular;\
    color: %1;\
    }").arg(themetext));
    dtime->label_3->setStyleSheet(QString("border:0px;\
    font-size:14px;\
    font-family: SourceHanSansSC-Regular;\
    color: %1;\
    }").arg(themetext));
    dtime->pushButton->setStyleSheet(QString("{\
    background-color:%1;\
    border-radius:10px;\
    border: 1px  solid %2;\
    }").arg(themebackground).arg(themeborder));
    dtime->line->setStyleSheet(QString("border: 1px  solid %1;").arg(themeborder));

    dtime->setVisible(true);
    tzone = new Timezone(this,m_haveTimedated);
    tzone->tzonesearch->setStyleSheet(QString("background-color:%1;\
    border-radius:10px;\
    border: 1px  solid %2;\
    padding-left:46px;").arg(themebackground).arg(themeborder));

    tzone->label->setStyleSheet(QString("font-size:14px;\
    font-family: SourceHanSansSC-Regular;\
    color: %1;\
    }").arg(themetext));

    tzone->m_local->setStyleSheet(QString("font-size:14px;\
    font-family: SourceHanSansSC-Regular;\
    color: %1;\
    }").arg(themetext));
    tzone->frame->setStyleSheet(QString("QFrame#frame{\
    background-color:%1;\
    border-radius:10px;\
    border: 1px  solid %2;\
    }").arg(themebackground).arg(themeborder));
    tzone->pushButton->setStyleSheet(QString("{\
    background-color:%1;\
    border-radius:10px;\
    border: 1px  solid %2;\
    }").arg(themebackground).arg(themeborder));
    tzone->setVisible(true);
    
    stack.addWidget(dtime);
    stack.addWidget(tzone);
    stack.setCurrentIndex(0);
    layout->addWidget(&stack, 0, Qt::AlignHCenter);
    connect(button1, &QPushButton::clicked, [&]() {
        stack.setCurrentIndex(1); 
    });
    connect(button2, &QPushButton::clicked, [&]() {
        stack.setCurrentIndex(2); 
    });

    //返回上一级
    connect(dtime->pushButton, &QPushButton::clicked, [&]() {
        stack.setCurrentIndex(0); 
    });
    connect(tzone->pushButton, &QPushButton::clicked, [&]() {
        stack.setCurrentIndex(0); 
    });


    connect(dtime, SIGNAL(timeChanged(bool)), this, SIGNAL(changed(bool)));
    connect(tzone, SIGNAL(timeChanged(bool)), this, SIGNAL(changed(bool)));
    connect(dtime,SIGNAL(FormatconfigChanged(bool)),this,SIGNAL(changed(bool)));

    connect(m_configWatcher.data(), &KConfigWatcher::configChanged, this, &KclockModule::handleDBusSignal);

    if (m_haveTimedated) {
        setAuthAction(KAuth::Action(QStringLiteral("org.freedesktop.timedate1.set-time")));
    } else {
        qWarning() << "Timedated not found, using legacy saving mode";
        setNeedsAuthorization(true);
    }
}

void KclockModule::kauthSave()
{
    QVariantMap helperargs;
    helperargs[QStringLiteral("ntp")] = true;
    helperargs[QStringLiteral("ntpServers")] = dtime->ntpServers();
    helperargs[QStringLiteral("ntpEnabled")] = dtime->ntpEnabled();

    if (!dtime->ntpEnabled()) {
        QDateTime newTime = dtime->userTime();
        qDebug() << "Set date to " << dtime->userTime();
        helperargs[QStringLiteral("date")] = true;
        helperargs[QStringLiteral("newdate")] = QString::number(newTime.toTime_t());
        helperargs[QStringLiteral("olddate")] = QString::number(::time(nullptr));
    }
    QString selectedTimeZone = tzone->selectedTimeZone();
    if (!selectedTimeZone.isEmpty()) {
        helperargs[QStringLiteral("tz")] = true;
        helperargs[QStringLiteral("tzone")] = selectedTimeZone;
    } else {
        helperargs[QStringLiteral("tzreset")] = true; // make the helper reset the timezone
    }


    Action action = authAction();
    action.setArguments(helperargs);

    ExecuteJob *job = action.execute();
    timedatedRc = job->exec();
    if (!timedatedRc) {
        KMessageBox::error(this, i18n("Unable to authenticate/execute the action: %1, %2", job->error(), job->errorString()));
    }

    if (timedatedRc) {
        QDBusMessage msg = QDBusMessage::createSignal(QStringLiteral("/org/kde/kcmshell_clock"), //
                                                      QStringLiteral("org.kde.kcmshell_clock"),
                                                      QStringLiteral("clockUpdated"));
        QDBusConnection::sessionBus().send(msg);
    }
    if (!m_haveTimedated) {
        QTimer::singleShot(5000, this, SLOT(load()));
    } else {
        load();
    }
}
void KclockModule::needSaveNtp()
{
    OrgFreedesktopTimedate1Interface timedateIface(QStringLiteral("org.freedesktop.timedate1"),
                                                   QStringLiteral("/org/freedesktop/timedate1"),
                                                   QDBusConnection::systemBus());
    if (dtime->ntpEnabledChanged()) {
        auto reply = timedateIface.SetNTP(dtime->ntpEnabled(), true);
        reply.waitForFinished();
        if (reply.isError()) {
            KMessageBox::error(this, i18n("Unable to change NTP settings"));
            qWarning() << "Failed to enable NTP" << reply.error().name() << reply.error().message();
            timedatedRc=false;
        }
    }

    QTimer::singleShot(1000,[&](){
        timedatedSave();
    });
}

void  KclockModule::timedatedSave()
{
    if (!dtime->userTimeChanged()) return;

    OrgFreedesktopTimedate1Interface timedateIface(QStringLiteral("org.freedesktop.timedate1"),
                                                   QStringLiteral("/org/freedesktop/timedate1"),
                                                   QDBusConnection::systemBus());
    if (!dtime->ntpEnabled()) {
        qint64 timeDiff = dtime->userTime().toMSecsSinceEpoch() - QDateTime::currentMSecsSinceEpoch();
        //*1000 for milliseconds -> microseconds
        auto reply = timedateIface.SetTime(timeDiff * 1000, true, true);
        reply.waitForFinished();
        qDebug()<<reply.error().name() << reply.error().message();
        if (reply.isError()) {
            KMessageBox::error(this, i18n("Unable to set current time"));
            qWarning() << "Failed to set current time" << reply.error().name() << reply.error().message();
            timedatedRc=false;
        }
    }
    QString selectedTimeZone = tzone->selectedTimeZone();
    if (!selectedTimeZone.isEmpty()) {
        auto reply = timedateIface.SetTimezone(selectedTimeZone, true);
        reply.waitForFinished();
        if (reply.isError()) {
            KMessageBox::error(this, i18n("Unable to set timezone"));
            qWarning() << "Failed to set timezone" << reply.error().name() << reply.error().message();
            timedatedRc=false;
        }
    }
    if (timedatedRc) {
        QDBusMessage msg = QDBusMessage::createSignal(QStringLiteral("/org/kde/kcmshell_clock"), //
                                                      QStringLiteral("org.kde.kcmshell_clock"),
                                                      QStringLiteral("clockUpdated"));
        QDBusConnection::sessionBus().send(msg);
    }
    if (!m_haveTimedated) {
        QTimer::singleShot(5000, this, SLOT(load()));
    } else {
        load();
    }
    m_hwclock->setHwclock();
}

void KclockModule::save(){
    setDisabled(true);
    timedatedRc = true;
    if (m_haveTimedated) {
       needSaveNtp();
    } else {
       kauthSave();
    }
    timedatedRc = false;

    KSharedConfig::Ptr config = KSharedConfig::openConfig("ktimezonedrc");
    KConfigGroup containmentGroup = config->group("TimeZones");
    containmentGroup.writeEntry("use24hFormat", dtime->m_ischecked ? 2 : 0, KConfigBase::Notify); // Default to 24-hour format
    config->sync();
    setDisabled(false);
}

//void KclockModule::save()
//{
//    setDisabled(true);
//    timedatedRc = true;

//    bool timeOrNtpChanged = dtime->hasTimeOrNtpChanges();
//    bool dateFormatChanged = dtime->hasDateFormatChanges();
//    bool tzChanged = tzone->hasTimezoneChanges();

//    qDebug() << "Date format changed:" << dateFormatChanged;
//    qDebug() << "Time/NTP changed:" << timeOrNtpChanged;
//    qDebug() << "Timezone changed:" << tzChanged;

//    // 处理日期格式变更
//    if (dateFormatChanged) {
//        dtime->updateConfigFile(dtime->m_ischecked);
//        dtime->saveConfig();
//        // 发送DBus信号通知格式变化
//        QDBusMessage signal = QDBusMessage::createSignal(
//            "/com/nfs/timeFormatChanged",
//            "com.nfs.timeFormatChanged",
//            "timeChangeSignal"
//        );
//        signal << dtime->m_ischecked;
//        QDBusConnection::sessionBus().send(signal);
//    }

//    // 处理时间和时区变更
//    if (timeOrNtpChanged || tzChanged) {
//        if (m_haveTimedated) {
//            needSaveNtp();
//        } else {
//            kauthSave();
//        }
//    }

//    // 重新加载配置并更新界面
//    if (!m_haveTimedated) {
//        QTimer::singleShot(5000, this, SLOT(load()));
//    } else {
//        load();
//    }

//    // 强制刷新时间显示
//    dtime->load();
//    Q_EMIT changed(false);
//}

void KclockModule::load()
{
    dtime->load();
    tzone->load();
    setDisabled(false);
}

void KclockModule::handleDBusSignal()
{
    int step = m_configWatcher->config()->group(QStringLiteral("TimeZones")).readEntry(QStringLiteral("use24hFormat"), 0);

    qDebug() << "void KclockModule::handleDBusSignal()被调用" << step;
}

#include "main.moc"
